package com.ls.httpstudy.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

@Service
public class WebClientToInterface {

    @Qualifier("defaultWebClient")
    @Autowired
    WebClient webClient;

    public String doGet(String httpUrl) {
        Mono<String> mono = webClient
                .method(HttpMethod.GET)
                .uri(httpUrl)
                .acceptCharset(StandardCharsets.UTF_8)
                //获取响应结果
                .retrieve()
                //将结果转换为指定类型
                .bodyToMono(String.class);

        return mono.block();
    }

    public String doPost(String httpUrl) {
//        Mono<String> mono = webClient.method(HttpMethod.POST).uri(httpUrl).retrieve().bodyToMono(String.class);
        Mono<String> mono = webClient
                .method(HttpMethod.POST)
                .uri(httpUrl)
                .acceptCharset(StandardCharsets.UTF_8)
                .contentType(MediaType.APPLICATION_JSON)  //JSON数据类型
                .body(BodyInserters.fromValue(""))  //JSON字符串数据
                .retrieve()
                .bodyToMono(String.class);
        return mono.block();
    }
}
